package com.donglu.autodatabase;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.FillLayout;

public class DatabaseAutoRun {

	protected Shell shell;
	private DatabaseConfig config=new DatabaseConfig();
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			DatabaseAutoRun window = new DatabaseAutoRun();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(686, 438);
		shell.setText("自动删除5000数据库图片");
		shell.setLayout(new GridLayout(1, false));
		shell.addDisposeListener(new DisposeListener() {
			@Override
			public void widgetDisposed(DisposeEvent e) {
				isStart=false;
			}
		});
		
		Composite composite = new Composite(shell, SWT.NONE);
		composite.setLayout(new GridLayout(7, false));
		
		Label lblNewLabel = new Label(composite, SWT.NONE);
		lblNewLabel.setText("删除数据");
		
		dt_deleteTime = new DateTime(composite, SWT.BORDER);
		dt_deleteTime.setMonth(dt_deleteTime.getMonth()-1);
		
		Label label_2 = new Label(composite, SWT.NONE);
		label_2.setText("前的数据");
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		
		Label label_1 = new Label(composite, SWT.NONE);
		label_1.setText("开始时间");
		
		dt_startTime = new DateTime(composite, SWT.BORDER | SWT.TIME);
		dt_startTime.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		Label label = new Label(composite, SWT.NONE);
		label.setText("停止时间:");
		
		dt_stopTime = new DateTime(composite, SWT.BORDER | SWT.TIME);
		
		Label label_3 = new Label(composite, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_3.setText("运行间隔:");
		
		txt_runSleep = new Text(composite, SWT.BORDER);
		txt_runSleep.setText("200");
		GridData gd_txt_runSleep = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_txt_runSleep.widthHint = 40;
		txt_runSleep.setLayoutData(gd_txt_runSleep);
		
		Label label_4 = new Label(composite, SWT.NONE);
		label_4.setText("毫秒");
		
		Composite composite_2 = new Composite(shell, SWT.NONE);
		composite_2.setLayout(new GridLayout(3, false));
		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		btn_start = new Button(composite_2, SWT.NONE);
		btn_start.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				start();
			}
		});
		btn_start.setText("开始删除");
		
		btn_stop = new Button(composite_2, SWT.NONE);
		btn_stop.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				isStart=false;
				setStartStatus();
			}
		});
		btn_stop.setText("停止删除");
		
		btn_config = new Button(composite_2, SWT.NONE);
		btn_config.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				new DatabaseConfigApp(config).open();
			}
		});
		btn_config.setText("配置");
		
		Composite composite_1 = new Composite(shell, SWT.NONE);
		composite_1.setLayout(new FillLayout(SWT.HORIZONTAL));
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		txt_msg = new Text(composite_1, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL);
		
		init();
	}
	private void init() {
		if (readFile()!=null) {
			config=(DatabaseConfig) readFile();
		}
	}
	
	public Object readFile(){
		String fileName="config.temp";
		File file = new File(fileName);
		if (!file.exists()) {
			return null;
		}
		try(ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file))) {
			return ois.readObject();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public boolean isStart=true;
	private DateTime dt_stopTime;
	private Text txt_msg;
	private DateTime dt_startTime;
	private DateTime dt_deleteTime;
	private Button btn_start;
	private Button btn_stop;
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat sdfMs=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	int runSleep=200;
	private Text txt_runSleep;
	private Button btn_config;
	protected void start() {
		isStart=true;
		Calendar c = Calendar.getInstance();
		c.set(dt_deleteTime.getYear(), dt_deleteTime.getMonth(), dt_deleteTime.getDay(), 0, 0, 0);
		final Date deleteTime=c.getTime();
		
		int stopHours = dt_stopTime.getHours();
		int stopMinutes = dt_stopTime.getMinutes();
		int stopSeconds = dt_stopTime.getSeconds();
		int startHours = dt_startTime.getHours();
		int startMinutes = dt_startTime.getMinutes();
		int startSeconds = dt_startTime.getSeconds();
		
		try {
			Integer integer = Integer.valueOf(txt_runSleep.getText());
			if (integer>200) {
				runSleep=integer;
			}else{
				runSleep=200;
			}
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		}
		
		List<String> sqls=getSql(deleteTime);
		new Thread(new Runnable() {
			public void run() {
				Calendar c1=Calendar.getInstance();
				
				while (isStart) {
					try {
						Date nowDate = new Date();
						c1.setTime(nowDate);
						c.set(c1.get(Calendar.YEAR),c1.get(Calendar.MONTH), c1.get(Calendar.DAY_OF_MONTH), startHours, startMinutes, startSeconds);
						Date startTime = c.getTime();
						c.set(c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DAY_OF_MONTH), stopHours, stopMinutes, stopSeconds);
						Date stopTime = c.getTime();
						System.out.println("nowDate="+sdf.format(nowDate)+"=startTime="+sdf.format(startTime)+"=stopTime="+sdf.format(stopTime)+"=deleteTime="+sdf.format(deleteTime));
						if (startTime.after(stopTime)) {
							if (nowDate.after(stopTime)&&nowDate.before(startTime)) {
								Thread.sleep(10000);
								continue;
							}
						}else{
    						if (nowDate.before(startTime)||nowDate.after(stopTime)) {
    							Thread.sleep(10000);
    							continue;
    						}
						}
						
						int updateSize=0;
						for (String sql : sqls) {
							setMessage("sqls=="+sql);
							String s = sql.substring(0, 10);
							if (s.contains("delete")||s.contains("update")) {
								int executeSQLUpdate = DatabaseUtil.executeSQLUpdate(config.getIp(), config.getPort(), config.getDatabaseName(), config.getUserName(), config.getPassword(), sql, DatabaseUtil.SQLSERVER2008);
								updateSize+=executeSQLUpdate;
							}else{
								DatabaseUtil.executeSQL(config.getIp(), config.getPort(), config.getDatabaseName(), config.getUserName(), config.getPassword(), sql, DatabaseUtil.SQLSERVER2008);
							}
						}
						
						setMessage(sdfMs.format(nowDate)+"-尝试操作数据库数据数据完成，花费时间："+(System.currentTimeMillis()-nowDate.getTime())+"毫秒，数据库数据改变数量："+(updateSize));

						Thread.sleep(runSleep);
					} catch (Exception e) {
						String message = e.getMessage();
						System.out.println(message);
						if (message.contains("数据库连接失败")) {
							isStart=false;
							setMessage("数据库连接失败，请检查配置是否正确。");
							break;
						}
					}
				}
				setStartStatus();
			}
		}).start();
		setStartStatus();
	}

	private List<String> getSql(Date deleteTime) {
		List<String> list = new ArrayList<>();
		File f=new File("sql");
		System.out.println(f.getAbsolutePath());
		if (f.exists()&&f.isDirectory()) {
			File[] files = f.listFiles();
			for (File file : files) {
				String s=readFile(file);
				if (s==null) {
					continue;
				}
				String[] split = s.split(";");
				for (String string : split) {
					if (string.trim().isEmpty()) {
						continue;
					}
					String replace = string.replace("{}", sdf.format(deleteTime));
					list.add(replace);
//					System.out.println(replace);
				}
			}
		}
		return list;
	}

	private String readFile(File file) {
		try(BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
			StringBuilder sb=new StringBuilder();
			String s=br.readLine();
			while (s!=null) {
//				System.out.println(s);
				if (s.contains("--")) {
					continue;
				}
				sb.append(s);
				s=br.readLine();
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void setStartStatus() {
		if (shell.isDisposed()) {
			System.exit(0);
		}
		shell.getDisplay().asyncExec(new Runnable() {
			public void run() {
				boolean enabled = !isStart;
				btn_start.setEnabled(enabled);
				btn_stop.setEnabled(isStart);
				btn_config.setEnabled(enabled);
				txt_runSleep.setEditable(enabled);
				dt_deleteTime.setEnabled(enabled);
				dt_startTime.setEnabled(enabled);
				dt_stopTime.setEnabled(enabled);
			}
		});
	}

	private void setMessage(String string) {
		if (shell.isDisposed()) {
			System.exit(0);
		}
		shell.getDisplay().asyncExec(new Runnable() {
			public void run() {
				if (txt_msg.isDisposed()) {
					return;
				}
				int lineCount = txt_msg.getLineCount();
				if (lineCount > 1000) {
					txt_msg.setText("");
				}
				txt_msg.append(string+"\t\n");
			}
		});
	}
}
